package com.niiwoo.civet.trade.service.local.notify;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.enums.NotifyTypeEnum;
import com.niiwoo.civet.user.service.SendSmsDubboService;
import com.niiwoo.civet.user.service.UserLetterDubboService;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Notifiers implements ApplicationContextAware {

    @Reference(version = "1.0.0")
    UserLetterDubboService userLetterDubboService;
    private ApplicationContext ctx;
    private Map<NotifyTypeEnum, AbstractNotifier> NOTIFIER_MAP = new HashMap<>();
    @Reference(version = "1.0.0")
    private SendSmsDubboService sendSmsDubboService;

    public <T> void notifyUser(NotifyTypeEnum type, T t) {
        Optional.ofNullable(NOTIFIER_MAP.get(type)).ifPresent(n -> n.notifyUser(t));
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        if (ctx.getParent() == null) {
            this.ctx = ctx;
        }
    }

    @PostConstruct
    public void initNotifiers() {
        Optional.ofNullable(ctx.getBeansOfType(AbstractNotifier.class))
                .map(Map::values)
                .ifPresent(list -> {
                    list.forEach(n -> {
                        n.setSendSmsDubboService(sendSmsDubboService);
                        n.setUserLetterDubboService(userLetterDubboService);
                        NOTIFIER_MAP.put(n.getType(), n);
                    });
                });
    }

}
